<?php
#[\Attribute]
class Route {
public function __construct(public string $path) {}
}
#[Route('/home')]
class HomeController {}
// Read
$ref = new ReflectionClass(HomeController::class);
$attr = $ref->getAttributes(Route::class)[0]->newInstance();
echo $attr->path; // /home
?>
Explain Enums in PHP 8.1+
Enums set fixed choices, like strings or numbers, for safe types over plain constants.
Why it matters: Cuts wrong values in lists.
<?php
enum Status: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
}
$status = Status::ACTIVE;
echo $status->value; // active
if ($status instanceof Status) { echo "Valid"; }
?>What is the Match Expression in PHP 8?
Match works like switch but is exact, covers all cases, and gives back a value. No extra jumps. Simpler than switch. At work: For check rules;
<?php
$status = 'error';
$result = match($status) {
'success' => 'OK',
'error' => 'Failed',
default => 'Unknown'
};
echo $result; // Failed
?>
How does JIT improve PHP performance?
Just-In-Time (PHP 8+) turns code to fast run form as it goes, making math or loops 20-50% quicker. Turn on with opcache.jit.
; php.ini
opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing
Best practices for SQL Injection prevention in PHP.
Use PDO ready queries and bind values. Clean outputs with htmlspecialchars().
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$_GET['id']]);
$user = $stmt->fetch();
echo htmlspecialchars($user['name']);
?>How to implement Caching in PHP apps?
Use Redis or Memcached for data holds. APCu for code speed.
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('key', 'value', 3600); // Holds 1 hour
echo $redis->get('key'); // value
?>Explain PHPUnit for Testing in PHP.
PHPUnit checks unit or full tests. Use checks for step-by-step builds.
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$this->assertEquals(4, 2 + 2);
}
}
// Run: phpunit CalculatorTest.php
?>What’s Microservices in PHP?
Split apps into small parts (like user or login via Symfony). Use Docker or Kafka for talks.
Example: Call with Guzzle:
<?php
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'http://auth-service/login', ['json' => ['user' => 'alex']]);
echo $response->getBody();
?>
What is the purpose of @ in PHP?
In PHP, @ is used for suppressing error messages. If any runtime error occurs on the line which consists @ symbol at the beginning, then the error will be handled by PHP.
What are the different types of Array in PHP?
There are 3 main types of arrays that are used in PHP:
- Indexed Array: An array with a numeric key is known as the indexed array. Values are stored and accessed in linear order.
- Associative Array: An array with strings for indexing elements is known as the associative array. Element values are stored in association with key values rather than in strict linear index order.
- Multidimensional Array: An array containing one or more arrays within itself is known as a multidimensional array. The values are accessed using multiple indices.
What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several projects of PHP?
Memcached is an efficient caching daemon designed specifically for decreasing database load in dynamic web applications. Memcache offers a handy procedural and object-oriented interface to Memcached.
Memcache is a memory storage space. We can run Memcache on a single or several servers. Therefore, it is possible to share a single instance of Memcache between multiple projects.
It is possible to configure a client to speak to a separate set of instances. Therefore, it is allowed to run two different Memcache processes on the same host. Despite running on the same host, both of such Memcache processes stay independent, unless there is a partition of data.
How to connect to a URL in PHP?
Any URL can be connected to PHP easily by making use of the library called cURL. This comes as a default library with the standard installation of PHP.
The term cURL stands for client-side URL. cURL make use of libcurl(client-side URL Transfer Library) which supports many protocols like FTP, FTPS, HTTP/1, HTTP POST, HTTP PUT, HTTP proxy, HTTPS, IMAP, Kerberos etc. It allows you to connect to a URL and retrieve and display information from that page – like the HTML content of the page, HTTP headers, and their associated data, etc.
//Step 1 To initialize curl
$ch = curl_init();
//Step 2 To set url where you want to post
$url = ‘http://www.localhost.com’;
//Step 3 Set curl functions which are needs to you
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELD,’postv1 = value1&postv2 = value2’);
//Step 4 To execute the curl
$result = curl_exec($ch);
//Step 5 Close curl
curl_close($ch);
Explain type hinting in PHP
In PHP, type hinting is used to specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration. It was introduced in PHP 5.
Whenever the function is called, PHP checks if the arguments are of a user-preferred type or not. If the argument is not of the specified type, the run time will display an error and the program will not execute.
It is helpful in better code organization and improved error messages.
//sendEmail() function argument $email is type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.
<?php
function sendEmail (Email $email)
{
$email->send();
}
?>
Leave a Comment